interface String {
  hashCode(): number;
}
interface Console {
  show(autoHide: boolean|void): void;
  setSize(w: number, h: number): void;
  setPosition(x:number, y:number): void;
  setBackgroud(color:string): void;
  setTitle(title: string, color: string, size:number): void;
  setLogSize(size: number): void;
  hide(): void;
  clear(): void;
}

exports.printLog = (data:string|object): void => {
  events.broadcast.emit('log', JSON.stringify(data))
}

exports.mainThreadsSleep = (delay: number = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, delay);
  });
}


exports.initConsole = async () => { 
  console.show()
  // await mainThreadsSleep()
  console.setSize(500, 300)
  console.setPosition(50, 200)
  console.setTitle("金币助手", "#ffffff", 40)
  // console.setLogSize(20)
  console.log("==================");
  console.log("      金币助手     ");
  console.log("==================");
}

/** 获取控件，依次向上寻找可点击控件
 * @param { object } selected - 控件选择器
 * @param { boolean } type - 是否使用集合
 */
exports.uiClick = (el: any, type: boolean = false):boolean|void => {
  let tags, tag
  if (!type) {
    tag = el.findOnce();
    if (!tag) return false
    let bool = true;
    while (bool) {
      let isBool = tag.click();
      if (isBool) {
        bool = false;
      } else {
        tag = tag.parent();
      }
    }
    return true
  } else {
    tags = el.find();
    if (!tags) return false
    tags.forEach((item: any) => {
      let tag = item
      let bool = true;
      while (bool) {
        let isBool = tag.click();
        if (isBool) {
          bool = false;
        } else {
          tag = tag.parent();
        }
      }
    })
  }

};

/**
 * 使用贝塞尔曲线生成拟人的滑动轨迹，并调用 gesture 实现滑动
 * @param {number} x1 起点x
 * @param {number} y1 起点y
 * @param {number} x2 终点x
 * @param {number} y2 终点y
 * @param {number} duration 滑动时长（毫秒）
 */
exports.humanLikeSwipe = (x1:number, y1:number, x2:number, y2:number, duration:number):void => {
  let r = 50
  x1 = random(x1 - r, x1 + r)
  y1 = random(y1 - r, y1 + r)
  x2 = random(x2 - r, x2 + r)
  y2 = random(y2 - r, y2 + r)
  duration = random(duration - 100, duration + 50)
  // 控制点随机偏移：制造滑动曲线
  let cp1 = [x1 + random(-100, 100), y1 + random(0, 300)];
  let cp2 = [x2 + random(-100, 100), y2 - random(0, 300)];
  console.log(cp1, cp2);
  let points = [];
  let steps = 50;

  for (let t = 0; t <= 1; t += 1 / steps) {
      // 贝塞尔公式 (三阶)
      let x = (1 - t) ** 3 * x1 +
              3 * (1 - t) ** 2 * t * cp1[0] +
              3 * (1 - t) * t ** 2 * cp2[0] +
              t ** 3 * x2;

      let y = (1 - t) ** 3 * y1 +
              3 * (1 - t) ** 2 * t * cp1[1] +
              3 * (1 - t) * t ** 2 * cp2[1] +
              t ** 3 * y2;

      points.push([Math.abs(x), Math.abs(y)]);
  }
  console.log(points);


  // 构建 gesture 参数
  let gestureArgs:Array<number|[number,number]> = [duration];
  for (let i = 0; i < points.length; i++) {
      gestureArgs.push([Math.floor(points[i][0]), Math.floor(points[i][1])]);
  }

  gesture.apply(null, gestureArgs);
}

exports.screenshot = ():any => {
  let img = auto.takeScreenshot()
  let base64 = images.toBase64(img)
  img.recycle()
  return images.fromBase64(base64)
}


/**
 * 智能平滑滑动到底 / 顶部
 * @param {UiObject} view 要滑动的控件（比如 RecyclerView）
 * @param {string} direction 滑动方向："down" 或 "up"
 * @param {number} maxTry 最大滑动次数，防止死循环
 */
function smartSmoothScroll(view: any, direction = "down", maxTry = 30) {
  if (!view) {
      toastLog("滑动失败：view 为空！");
      return false;
  }
  let bounds = view.bounds();
  let lastHash = null;
  
  for (let i = 0; i < maxTry; i++) {
      // 获取当前界面内容哈希（粗略判断有没有变化）
      let currentHash = hashNode(view);

      if (lastHash !== null && lastHash === currentHash) {
          // 没变化，说明已经滑到头了
          toastLog(`滑动完成，总共滑动 ${i} 次`);
          return true;
      }
      lastHash = currentHash;

      // 模拟真人滑动
      if (direction === "down") {
          // 向下滑
          gesture(
              random(200, 400), // 滑动时间
              [bounds.centerX(), bounds.bottom - random(10, 50)],
              [bounds.centerX(), bounds.top + random(10, 50)]
          );
      } else if (direction === "up") {
          // 向上滑
          gesture(
              random(200, 400),
              [bounds.centerX(), bounds.top + random(10, 50)],
              [bounds.centerX(), bounds.bottom - random(10, 50)]
          );
      } else {
          toastLog("未知滑动方向: " + direction);
          return false;
      }

      sleep(random(500, 800)); // 等待滑动完成
  }
  toastLog("滑动未完成，达到最大尝试次数");
  return false;
}

/**
* 生成节点简单哈希值，用来判断界面变化
* @param {UiObject} view 
*/
function hashNode(view:  any) {
  try {
      let children = view.children();
      let textList = [];
      for (let i = 0; i < children.size(); i++) {
          let child = children.get(i);
          if (child) {
              textList.push(child.text() + "_" + child.id());
          }
      }
      return textList.join("|").hashCode();
  } catch (e) {
      return Math.random(); // 遇到异常返回随机数
  }
}

// 给 String 加一个 hashCode 方法（标准 Java 字符串哈希算法）
String.prototype.hashCode = function () {
  var hash = 0;
  if (this.length == 0) return hash;
  for (var i = 0; i < this.length; i++) {
      var char = this.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // Convert to 32bit integer
  }
  return hash;
}


/**
 * 模拟人类自然手指点击 + 微滑动
 * @param {number} x1 左上角X
 * @param {number} y1 左上角Y
 * @param {number} x2 右下角X
 * @param {number} y2 右下角Y
 */
exports.humanLikeGesture = (x1:number, y1:number, x2:number, y2:number) => {
  // 随机起点
  let startX = random(x1, x2);
  let startY = random(y1, y2);

  // 小范围滑动偏移（模拟手指晃动）
  let offsetX = random(-10, 10);
  let offsetY = random(-10, 10);

  // 生成曲线路径
  let midX = (startX + startX + offsetX) / 2 + random(-5, 5);
  let midY = (startY + startY + offsetY) / 2 + random(-5, 5);

  let duration = random(100, 250); // 按下时间
  gesture(
      duration,
      [startX, startY],
      [midX, midY],
      [startX + offsetX, startY + offsetY]
  );

  // 有一定概率模拟手抖，点一下又抖一下
  if (random(0, 100) < 20) {
      sleep(random(30, 80));
      gesture(
          random(80, 160),
          [startX + offsetX, startY + offsetY],
          [startX + offsetX + random(-8, 8), startY + offsetY + random(-8, 8)]
      );
  }
}




